import fetch from '../utils/fetch';
import { message } from 'antd';
import config from '../config';
import { ADMIN_EDIT } from '../actionTypes';

export const updateEdit = (payload) => ({
  type: ADMIN_EDIT,
  payload,
});

export const getDetailById = (id) => async (dispatch) => {
  if (!id || !/^\d+$/g.test(id)) {
    return false;
  }
  const detail = await fetch({
    url: `${config.HOST}/admin/lesson/id/${id}`,
  });

  if (detail.code === 200) {
    let data = detail.data;
    data.content = JSON.parse(data.content);
    dispatch(updateEdit(data));
  } else {
    message.error('获取数据失败');
  }
};

export const changeName = (e) => (dispatch) => {
  dispatch(updateEdit({
    name: e.target.value,
  }));
};

export const changeType = (e) => (dispatch) => {
  dispatch(updateEdit({
    type: e.target.value,
  }));
};

export const changeAvatar = (e) => (dispatch) => {
  dispatch(updateEdit({
    avatar: e.target.value,
  }));
};

export const change = (e = null, obj) => (dispatch, getState) => {
  const { edit } = getState().admin;
  const content = [...edit.content] || [];
  const index = content.findIndex(item => item.id === obj.id);
  const val = {
    ...obj,
    content: e ? e.target.value : '',
  };
  if (index === -1) {
    content.push(val);
  } else {
    content.splice(index, 1, val);
  }
  dispatch(updateEdit({
    content,
  }));
};

export const del = (obj) => (dispatch, getState) => {
  const { edit } = getState().admin;
  const content = [...edit.content] || [];
  const index = content.findIndex(item => item.id === obj.id);
  content.splice(index, 1);
  dispatch(updateEdit({
    content,
  }));
};

export const submit = (cb) => async (dispatch, getState) => {
  const { edit } = getState().admin;
  const { id, name, type, avatar, content } = edit;
  if (content.length === 0) {
    message.error('至少添加一条');
    return false;
  }

  for (let i = 0, len = content.length; i < len; i++) {
    if (content[i].content === '') {
      message.error('请填写完整后提交.');
      return false;
    }
  }

  const addRes = await fetch({
    method: 'post',
    url: `${config.HOST}/admin/lesson/edit`,
    param: {
      id,
      name,
      type,
      avatar,
      content,
    },
  });
  if (addRes.code === 200) {
    cb();
    message.success('修改课程成功');
  } else {
    message.error('修改课程失败');
  }
};
